$(function(){
	findCompany();
});

/**
 * 查询分公司类型下拉框
 * @returns
 */
function findCompany(){
	$("#bar").html("");
	var url="../../UserAction/findbyName.action";
	var data=null;
	$.post(url,data,function(mes){
		$("#bar").append("<option value=''>====请选择====</option>");
		$.each(mes,function(index,item){
			$("#bar").append("<option value="+item.braId+">"+item.braName+"</option>");
			load();
		});
	},"json");
}
/**
 * 查询用户角色
 * @returns
 */
function findName(){
	$("#ron").html("");
	var url="../../UserAction/findAll.action";
	var data=null;
	$.post(url,data,function(mes){
		$.each(mes,function(index,item){
			$("#ron").append("<input type='checkbox' name='check' value='"+item.roId+"' title='"+item.roName+"' lay-filter='allChoose' >");
			load();
		})
	},"json");
}
/**
 * 修改查询用户角色权限
 */
function selectName(id){
	$("#roId").val("");
	var url="../../UserAction/selectName.action";
	var data={"userId":id};
	$.post(url,data,function(mes){
		$.each(mes,function(index,item){
			$("input[name='check']").each(function(){ 
        		if ($(this).val() == item.roId) {
        			$(this).prop("checked",true);
        			var str = "";
          			str+=$(this).val()+"@";
          			$("#roId").val($("#roId").val()+str);
        		} 
    		});
			load();
		})
	},"json");
}



/**
 * 取到复选框ID
 * @param id
 * @returns
 */
function getId(id){
	alert(id);
}
var userId;
function exit(){
	$("#userNames").removeClass("layui-input layui-disabled");
	$("#userNames").addClass("layui-input");
	$("#bar").removeAttr("disabled");
	$("#bar").val("");
	$("#userId").val("");
	$("#userNames").val("");
	$("#userPwd").val("");
	//清除单选框被选中的值
	$("input[type='radio']").removeAttr('checked');
	$("#userPhone").val("");
	$("#userEmail").val("");
	$("#userState").val("");
	$("#optime").val("");
	$("#img").attr({"src":""});
	load();
	//关闭左右页面层
	layer.closeAll('page');
}
layui.use(['form', 'layedit', 'laydate','table','upload'], function(){
  var table = layui.table
  ,laydate = layui.laydate
  ,form = layui.form
  ,layer = layui.layer
  ,layedit = layui.layedit
  ,upload = layui.upload;
  

	  
  /**
   * 复选框点击事件
   */
  	form.on('checkbox(allChoose)', function(obj){
  		if(obj.elem.checked == true) {
  			var str = "";
  			str+=obj.value+"@";
  			$("#roId").val($("#roId").val()+str);
  		} else {
  			 //取得文本框的值
			 var aa = $("#roId").val();
			 //把文本框清空
			 $("#roId").val("")
			 //文本框的值按取消复选框的id来去除
			 var bb = aa.replace(obj.value+"@",'');
			 //把值重新赋给文本框
			 $("#roId").val(bb);
  		}
	});
  	
//普通图片上传
	var uploadInst = upload.render({
		elem: '#userImage'
			,url: '/upload/'
				,auto:0
				,choose: function(obj){
					//预读本地文件示例，不支持ie8
					obj.preview(function(index, file, result){
						$('#img').attr('src', result); //图片链接（base64）
						$("#img").css({"width":"35px","height":"35px"});
					});
				}
	});
  
  //监听工具条
  table.on('tool(demo)', function(obj){
    var da = obj.data;
    if(obj.event === 'edit'){
    	$("#bar").attr({"disabled":"disabled"});
    	$("#userNames").removeClass("layui-input");
    	$("#userNames").addClass("layui-input layui-disabled");
    	findName();
    	var url="../../UserAction/findById.action";
        var data={"userId":da.userId};
        $.post(url,data,function(mes){
        	layer.open({
    	        type: 1	 //此处以iframe举例
    	        ,title: '数据修改'
    	        ,area: ['620px', '500px']
        		,offset: 'auto'
    	        ,content:$('#addOrUpdate')
    	        ,success: function(layero){
    	        	$("#userId").val(mes.userId);
    	        	$("#bar").val(mes.braId);
    	        	$("#userNames").val(mes.userName);
    	        	$("#userPwd").val(mes.userPwd);
    	        	$("#userPhone").val(mes.userPhone);
    	        	$("#userEmail").val(mes.userEmail);
    	        	
    	        	$("input[name='userSex']").each(function(){ 
                		if ($(this).val() == mes.userSex) {
                			$(this).prop("checked",true);
                		} 
            		});
    	        	
    	        	
    	        	$("#optime").val(mes.optime);
    	        	$("#img").attr({"src":"../../"+mes.userImage});
    	        	selectName(da.userId);
    	        	//渲染
    	        	load();
        		},end : function() {
    	        	//弹框关闭的回调函数
    				$("#addOrUpdate").hide();
    				exit();
    			}
    	    });
        	
        },"json");
    }else if(obj.event === 'del'){
        layer.confirm('真的删除行么', function(index){
        	var url="../../UserAction/delete.action";
        	var data={"userId":da.userId}
        	$.post(url,data,function(mes){
        		if(mes==1){
        			obj.del();
                    layer.close(index);
                    layer.msg("删除成功");
        		}else{
        			layer.msg("删除失败");
        		}
        	},"json");
            
          });
        }
  });
  
  
  var $ = layui.$, active = {
		    reload: function(){
		      var oper = $('#oper');
		      var state= $('#state');
		      var userName=  $('#userName');
		      //执行重载
		      table.reload('idTest', {
		        page: {
		          curr: 1 //重新从第 1 页开始
		        }
		        ,where: {
		        	oper: oper.val(),
		        	userState:state.val(),
		        	userName:userName.val() 
		        }
		      });
		    }
		  };
  
		  $('.demoTable .layui-btn').on('click', function(){
		    var type = $(this).data('type');
		    active[type] ? active[type].call(this) : '';
		  });
		 
		  $('.demoTable #insert').on('click', function(){
			  
			  findName();
			  layer.open({
	    	        type: 1	 //此处以iframe举例
	    	        ,title: '数据增加'
	    	        ,offset: 'auto'
	    	        ,area: ['620px', '500px']
	    	        ,content:$('#addOrUpdate')
	    	        ,end : function() {
	    	        	//弹框关闭的回调函数
	    				$("#addOrUpdate").hide();
	    				exit();
	    			}
	    	    });
		  });
});

function filiale(){
	var str=document.getElementById("bar");
	if(str.value==""){
		 parent.layer.msg('请选择分公司', {
		      icon: 5,
		      anim :6
		  });
	return false;
	}
	return true;
	}

//表单验证
function snUserName(){
	layui.use(['form', 'layedit', 'laydate','table'], function(){
		var layer = layui.layer;
		if($("#userNames").val()==null || $("#userNames").val()==''){
			 parent.layer.msg('用户姓名不能为空', {
			      icon: 5,
			      anim :6
			  });
			 $("#NameYz").val("×");
		}else{
			var url="../../UserAction/findBrandByName.action";
			var data={"name":$("#userNames").val()};
			$.post(url,data,function(mes){
				if(mes.state==1){
					 parent.layer.msg('用户名已存在', {
					      icon: 5,
					      anim :6
					  });
					 $("#NameYz").val("×");
				}else{
					$("#NameYz").val("√");
				}
			},"json")
			
		}
	});
}

function snPwd(){
	layui.use(['form', 'layedit', 'laydate','table'], function(){
		var layer = layui.layer;
		if($("#userPwd").val()==null || $("#userPwd").val()==''){
			 parent.layer.msg('密码不能为空', {
			      icon: 5,
			      anim :6
			  });
			 $("#PwdYz").val("×");
		}else if(isNaN($("#userPwd").val())){
			 parent.layer.msg('用户密码只能是数字', {
			      icon: 5,
			      anim :6
			  });
			 $("#PwdYz").val("×");
		}else{
			 $("#PwdYz").val("√");
		}
		
	});
}

function snPhone(){
	layui.use(['form', 'layedit', 'laydate','table'], function(){
		var layer = layui.layer;
		if($("#userPhone").val()==null || $("#userPhone").val()==''){
			 parent.layer.msg('手机号码不能为空', {
			      icon: 5,
			      anim :6
			  });
			 $("#PhoneYz").val("×");
		}else if(isNaN($("#userPhone").val())){
			 parent.layer.msg('手机号码只能是数字', {
			      icon: 5,
			      anim :6
			  });
			 $("#PhoneYz").val("×");
		}else{
			 $("#PhoneYz").val("√");
		}
		
	});
}
function snEmali(){
	var useremail=document.getElementById("userEmail");
	var pattern = /^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
	var spans=document.getElementsByTagName("span")[0];
	layui.use(['form', 'layedit', 'laydate','table'], function(){
		var layer = layui.layer;
		if($("#userEmail").val()==null || $("#userEmail").val()==''){
			 parent.layer.msg('邮箱不能为空', {
			      icon: 5,
			      anim :6
			  });
			 $("#EmailYz").val("×");
		}else if(!pattern.test(useremail.value)){
			 parent.layer.msg('请输入正确的邮箱格式', {
			      icon: 5,
			      anim :6
			  });
			 $("#PhoneYz").val("×");
		}else{
			 $("#EmailYz").val("√");
	    }
		
	});
}

function buttonSubmit(){
	snEmali();
	snPhone();
	snPwd();
	filiale();
	var countyz=0;
	$.each($(".fromYz"),function(index,item){
		if($(item).val()=="√"){
			countyz++;  	
		}
	});
	var str=myform.userId.value;  
	if(str == ""){
		snUserName();
		snEmali();
		snPhone();
		snPwd();
		filiale();
		var countyz=0;
		$.each($(".fromYz"),function(index,item){
			if($(item).val()=="√"){
				countyz++;  	
			}
		});
		if(countyz==4){
			$("#myform").submit();		
		}
	}else{
		snEmali();
		snPhone();
		snPwd();
		filiale();
		var countyz=0;
		$.each($(".fromYz"),function(index,item){
			if($(item).val()=="√"){
				countyz++;  	
			}
		});
		if(countyz==3){
			$("#myform").submit();	 	
		}
	}
	
}


function load() {
	 var form = layui.form
	 form.render();
}